package com.example.healkep.fragment.bg;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.healkep.LoginActivity;
import com.example.healkep.datepicker.CustomDatePicker;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.example.healkep.R;
import com.example.healkep.datepicker.DateFormatUtils;

public class FragmentInputAD2 extends Fragment {

    private String id;
    private int bg_year, bg_month, bg_day;
    private TextView mTvSelectedTime;
    private CustomDatePicker mTimerPicker;

    @Override
    public View onCreateView(final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final Intent intent = getActivity().getIntent();
        id = intent.getStringExtra("username");
        bg_day = intent.getIntExtra("bg_day", -1);
        bg_month = intent.getIntExtra("bg_month", -1);
        bg_year = intent.getIntExtra("bg_year", -1);

        final View view = inflater.inflate(R.layout.bg_fragment_input,
                container, false);
        initView(view);
        return view;
    }

    private void initTimerPicker() {
        String beginTime = "2018-00-00 00:00";
        String endTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);

        String year_bg, month_bg, day_bg;
        year_bg = Integer.toString(bg_year);
        if (bg_month < 10) {
            month_bg = "0" + Integer.toString(bg_month);
        } else {
            month_bg = Integer.toString(bg_month);
        }
        if (bg_day < 10) {
            day_bg = "0" + Integer.toString(bg_day);
        } else {
            day_bg = Integer.toString(bg_day);
        }

        String endTime2 = (year_bg + "-" + month_bg + "-" + day_bg + " 20:00").toString();
        if(DateFormatUtils.long2Str(System.currentTimeMillis(), false).equals(year_bg + "-" + month_bg + "-" + day_bg))
            mTvSelectedTime.setText(endTime);
        else
            mTvSelectedTime.setText(endTime2);

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker = new CustomDatePicker(getContext(), new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                mTvSelectedTime.setText(DateFormatUtils.long2Str(timestamp, true));
            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);
    }

    private void initView(View view) {

        final EditText bg_value = (EditText) view.findViewById(R.id.bg_value);
        LinearLayout ll_time = (LinearLayout) view.findViewById(R.id.ll_time);
        ll_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 日期格式为yyyy-MM-dd HH:mm
                mTimerPicker.show(mTvSelectedTime.getText().toString());
            }
        });
        mTvSelectedTime = view.findViewById(R.id.tv_selected_time);
        initTimerPicker();

        Button button = view.findViewById(R.id.send);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            MediaType JSON = MediaType.parse("application/json");
                            JSONObject json = new JSONObject();
                            try {
                                json.put("username", id);
                                json.put("bg_value", bg_value.getText());
                                json.put("time", mTvSelectedTime.getText());
                                json.put("time_slot", 9);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            OkHttpClient client = new OkHttpClient();  //创建http客户端
                            RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                            Request request = new Request.Builder()
                                    .url(LoginActivity.url+"/bg/add")
                                    .post(requestBody)
                                    .build();    //创造http请求
                            Response response = client.newCall(request).execute();  //执行发送的指令
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "上传成功！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
    }
}




